import pygame
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")

# 设置颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)


# 定义飞机类
class Plane(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([50, 30])
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.x = screen_width // 2
        self.rect.y = screen_height - 40
        self.change_x = 0

    def update(self):
        self.rect.x += self.change_x
        if self.rect.x < 0:
            self.rect.x = 0
        if self.rect.x > screen_width - 50:
            self.rect.x = screen_width - 50

    def go_left(self):
        self.change_x = -5

    def go_right(self):
        self.change_x = 5

    def stop(self):
        self.change_x = 0

    # 定义敌人类


class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([40, 25])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, screen_width - 40)
        self.rect.y = -40
        self.speed = random.randint(1, 3)

    def update(self):
        self.rect.y += self.speed
        if self.rect.y > screen_height:
            self.rect.y = -40
            self.rect.x = random.randint(0, screen_width - 40)
            self.speed = random.randint(1, 3)

        # 初始化敌机精灵组和飞机精灵组


all_sprites = pygame.sprite.Group()
plane = Plane()
all_sprites.add(plane)
enemies = pygame.sprite.Group()
for i in range(5):
    enemy = Enemy()
    all_sprites.add(enemy)
    enemies.add(enemy)

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                plane.go_left()  # 修正缩进，并添加调用plane的go_left方法
            elif event.key == pygame.K_RIGHT:
                plane.go_right()  # 修正缩进，并添加调用plane的go_right方法
            elif event.key == pygame.K_SPACE:
                # 在这里添加发射子弹的逻辑（如果已经定义了子弹类）
                pass  # 暂时留空

    # ...（其他游戏逻辑，如更新、渲染等）

    # 更新精灵组
    all_sprites.update()

    # 清除屏幕
    screen.fill(WHITE)

    # 绘制精灵组
    all_sprites.draw(screen)

    # 更新屏幕显示
    pygame.display.flip()

    # 控制帧率
    pygame.time.Clock().tick(60)

# 退出pygame
pygame.quit()
